﻿#region

using System;
using System.Diagnostics;
using PostSharp.Aspects;

#endregion

namespace AopAndIocDemo.Biz.Aspect
{
    [Serializable]
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
    public sealed class LoggingAspect : OnMethodBoundaryAspect
    {
        [NonSerialized]
        private Stopwatch _stopWatch;

        public string ControllerName { get; set; }
        public string ActionName { get; set; }
        public string Msg { get; set; }

        public override void OnEntry(MethodExecutionArgs args)
        {
            _stopWatch = Stopwatch.StartNew();
            base.OnEntry(args);
        }

        public override void OnException(MethodExecutionArgs args)
        {
            string msg = String.Format("Exception in :[{0}],Message:[{1}]", args.Method, args.Exception.Message);
            LoggHelper.WriteLog(LogType.Error,msg);
            args.FlowBehavior = FlowBehavior.Continue;

            base.OnException(args);
        }

        public override void OnSuccess(MethodExecutionArgs args)
        {
            string msg = string.Format("【{0}】 execute Completed.", new StackTrace().GetFrame(1).GetMethod().Name);
            LoggHelper.WriteLog(LogType.Trace, msg);

            base.OnSuccess(args);
        }

        public override void OnExit(MethodExecutionArgs args)
        {
            string msg = string.Format("[{0}] took {1}ms to execute.", new StackTrace().GetFrame(1).GetMethod().Name,
                   _stopWatch.ElapsedMilliseconds);
            LoggHelper.WriteLog(LogType.Trace, msg);

            base.OnExit(args);
        }
    }
}
